#!/bin/sh
#
# enumstr.sh - a tool generating a function mapping enumerator to its
# string representation
#
# Copyright (C) 2019 Masatake YAMATO
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Usage:
#
#  ./enumstr.sh <input-file> <enum-name> <fname> [PREFIX_FOR_TRIMMING] [--use-lower-bits-as-is]
#
# Example:
#
#   bash ./misc/enumstr.sh parsers/jscript.c eTokenType tokenTypeName
#
column_width=20

echo 'static const char *'"$3"'(enum '$2' e)'
printf '{ /* Generated by misc/enumstr.sh with cmdline:\n'
printf '     %s */\n' "$*"
echo '	switch (e)'
echo '	{'
./ctags --quiet --options=NONE --sort=no -o - --languages=C --kinds-C=e -x --_xformat="%N enum:%s" $1 | grep $2 | while read N S; do
	n=$N
	if [ -n "$4" ]; then
		n=${N#$4}
	fi
	printf "		case %${column_width}s: return %s;\n" "$N" "\"$n\""
done
shift 4
if [[ $1 == "--use-lower-bits-as-is" ]]; then
	printf '		default: %'"$((${column_width} + 3))s;\n" "break"
else
	printf '		default: %'"$((${column_width} - 3))s return %s;\n" ' ' "\"UNKNOWN\""
fi
echo '	}'
if [[ $1 == "--use-lower-bits-as-is" ]]; then
echo '	static char buf[3];'
echo '	if (isprint (e))'
echo '	{'
echo '		buf[0] = e;'
echo "		buf[1] = '\0';"
echo '	}'
echo "	else if (e == '\\n')"
echo '	{'
echo "		buf[0] = '\\\';"
echo "		buf[1] = 'n';"
echo "		buf[2] = '\0';"
echo '	}'
echo '	else'
echo '	{'
echo "		buf[0] = '\0';"
echo '	}'
echo '	return buf;'
fi
echo '}'
